define(['jquery', 'backbone'], function($, Backbone) {

  var Router = Backbone.Router.extend({
    initialize: function (opts) {
      this.defaults = {
        views: [],
        baseZIndex: 1,
        currentView: '',
        firstLoad: true,
        defaultIndex: opts.index,
        root: opts.root,
        type: opts.type
      }
      $.extend(this.defaults, opts.opts);
    },

    routes: {
      '*path(?*queryString)': 'any'
    },

    any: function (path, queryString) {
      var querys = {};
      if (queryString) {
        $.each(queryString.split('&'), function (i, str) {
          if (!str) return;
          var data = str.split('=');
          querys[data[0]] = data[1];
        })
      }
      switch (this.defaults.type.toLowerCase()){
        case 'stackview':
          StackView(path, querys, this.defaults);
          break;
        case 'singleview':
          SingleView(path, querys, this.defaults);
          break;
        default:
          SingleView(path, querys, this.defaults);
      }
    }
  });

  var loadView = function (paths, success) { 
    require(['text!' + paths + '.html'], function (html) {
      var root = $(html);
      var $root = $(root);
      var value = $root.attr('data-view');
      require([value], function(view) {
        success(view, $root);
      }, function(err) {
        console.log(err)
        console.error('找不到 ' + value + '.js');
      });
    }, function(err) {

      console.error('找不到 ' + paths + '.html');
    });
  }

  var StackView = function (paths, querys, defaults) {
    var path = (paths === null) ? defaults.defaultIndex : paths;
    loadView(path, function(view, $root){
      var viewsLength = defaults.views.length;
      if (viewsLength > 1 && (defaults.views[viewsLength - 2].path === path)) {
        var currentView = defaults.views[defaults.views.length - 1];
        currentView.viewClass.animateSlideOutRight(function(){
          currentView.viewClass.hide();
          currentView.$view.remove();
          currentView.viewClass = null;
          defaults.views[viewsLength - 2].viewClass.show();
          defaults.views.pop();
          defaults.baseZIndex--;
        });
      } else {
        defaults.root.append($root);
        var prevPath = viewsLength >= 1 ? defaults.views[viewsLength - 1].path : undefined;
        var viewclass = new view(querys, prevPath);
        viewclass.show();
        $root.css({
          'position': 'absolute',
          'top': 0,
          'left': 0,
          'z-index': defaults.baseZIndex++
        });
        if (!defaults.firstLoad) {
          viewclass.animateSlideInRight()
        }
        if (viewsLength >= 1) {
          defaults.views[viewsLength - 1].viewClass.hide();
        }
        defaults.views.push({path: path, viewClass: viewclass, $view: $root});
      }
      defaults.firstLoad = false;
    });
  }

  // var SingleView = function (paths, querys, defaults) {
  //   var path = (paths === null) ? defaults.defaultIndex : paths;
  //   loadView(path, function(view, $root){
  //     var viewsLength = defaults.views.length;
  //     defaults.root.append($root);
  //     var prevPath = viewsLength >= 1 ? defaults.views[viewsLength - 1].path : undefined;
  //     var viewclass = new view(querys, prevPath);
  //     viewclass.show();
  //     if (defaults.firstLoad) {
  //       viewclass.animateFadeIn();
  //     }
  //     defaults.views.push({path: path, viewClass: viewclass, $view: $root});
  //     if (viewsLength >= 1) {
  //       var prevView = defaults.views[viewsLength - 1];
  //       prevView.$view.remove();
  //       prevView.viewClass.hide();
  //       prevView.viewClass = null;
  //       defaults.views.shift();
  //     }
  //     defaults.firstLoad = false;
  //   })
  // }

  var SingleView = function (paths, querys, defaults) {
    var path = (paths === null) ? defaults.defaultIndex : paths;
    loadView(path, function(view, $root){
      var viewsLength = defaults.views.length;
      var prevPath = viewsLength >= 1 ? defaults.views[viewsLength - 1].path : undefined;
      if (viewsLength > 1 && (defaults.views[viewsLength - 2].path === path)) {
        var currentView = defaults.views[defaults.views.length - 1];
        currentView.viewClass.hide();
        currentView.$view.remove();
        currentView.viewClass = null;
        defaults.root.append(defaults.views[viewsLength - 2].$view);
        new defaults.views[viewsLength - 2].view(querys, prevPath);
        defaults.views[viewsLength - 2].viewClass.show();
        defaults.views.pop();
        console.log(defaults.views);
      } else {
        defaults.root.append($root);
        var viewclass = new view(querys, prevPath);
        viewclass.show();
        if (viewsLength >= 1) {
          defaults.views[viewsLength - 1].viewClass.hide();
          defaults.views[viewsLength - 1].$view.remove();
          defaults.views[viewsLength - 1].scrollY = window.scrollY;
        }
        defaults.views.push({path: path, viewClass: viewclass, $view: $root, view: view});
      }
      defaults.firstLoad = false;
    });
  }

  return {
    start: function (opts) {
      var $viewContainer = $('div[role="view-container"]');
      var type = $viewContainer.data('type') || 'SingleView';
      var index = $viewContainer.data('index') || 'views/home';
      if ($viewContainer.length <= 0) {
        console.error('没有找到 <div role="view-container"> 作为 view 的容器')
      } else {
        var router = new Router({root: $viewContainer, type: type, index: index, opts: opts});
        Backbone.history.start();
      }
    }
  }
})